package com.rdgk.newtech.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rdgk.newtech.dao.TransDao;
import com.rdgk.newtech.service.TransService;
import com.rdgk.newtech.util.StringTools;
import com.rdgk.newtech.util.translate.TransApi;
import com.rdgk.newtech.util.translate.TransUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: msun
 */
@Service
public class TransServiceImpl implements TransService {
    @Autowired
    private TransDao transDao;

    private static final String APP_ID = "20190813000326226";
    private static final String SECURITY_KEY = "F3l9TZkztVSR5ttuCHfL";
    private static final TransApi api = new TransApi(APP_ID, SECURITY_KEY);
    private final String paper_txt[] = new String[]{"title","keywords","abstract","authors","authors_affi"};
    private final String patent_txt[] = new String[]{"title"};
    private final String article_txt[] = new String[]{"title","abstract","content"};


    @Override
//    @Transactional(rollbackFor = Exception.class)
    public int transPaper() {
        JSONObject parameter_o = new JSONObject();
        int max_id = 0;
        try {
            max_id = transDao.getPaperMaxId();
        }catch (Exception e){
            max_id = 0;
        }
        parameter_o.put("max_id", max_id);
        List<JSONObject> paperList = transDao.listPaper(parameter_o);

        String query;

        JSONObject midPaper = paperList.get(0);
        String title;
        String keywords;
        String abstracts;
        String authors;
        String authors_affi;

        for (JSONObject o : paperList) {
            query = "";
            midPaper.put("id",o.getIntValue("id"));
            title = o.getString(paper_txt[0]);
            keywords = o.getString(paper_txt[1]);
            abstracts = o.getString(paper_txt[2]);
            authors = o.getString(paper_txt[3]);
            authors_affi = o.getString(paper_txt[4]);

            query = query + constructQuery(query,title) + constructQuery(query,keywords) + constructQuery(query,abstracts)
                    + constructQuery(query,authors) + constructQuery(query,authors_affi);

            midPaper = constructMapperParameters(query, midPaper, 0);
            transDao.addTransPaper(midPaper);

            try {
                TimeUnit.SECONDS.sleep(3);
            }catch (InterruptedException e){
                e.getStackTrace();
            }
        }
        return 0;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public int transPatent() {
        JSONObject parameter_o = new JSONObject();
        int max_id = 0;
        try {
            max_id = transDao.getPatentMaxId();
        }catch (Exception e){
            max_id = 0;
        }
        parameter_o.put("max_id", max_id);
        List<JSONObject> patentList = transDao.listPatent(parameter_o);

        String title;

        JSONObject midPaper = patentList.get(0);

        for (JSONObject o:patentList) {
            midPaper.put("id",o.getIntValue("id"));
            title = removeN(o.getString(patent_txt[0]));

            constructMapperParameters(title, midPaper, 1);
            transDao.addTransPatent(midPaper);

            try {
                TimeUnit.SECONDS.sleep(1);
            }catch (InterruptedException e){
                e.getStackTrace();
            }

        }
        return 0;
    }

    @Override
    public int transTecArticle() {
        JSONObject parameter_o = new JSONObject();
        int max_id = 0;
        try {
            max_id = transDao.getTransTecMaxId();
        }catch (Exception e){
            max_id = 0;
        }
        parameter_o.put("max_id", max_id);
        List<JSONObject> articleList = transDao.listTecArticle(parameter_o);
        String query;

        JSONObject midPaper = articleList.get(0);
        String title;
        String abstracts;
        String content;

        for (JSONObject o : articleList) {
            query = "";
            midPaper.put("id",o.getIntValue("id"));
            title = o.getString(article_txt[0]);
            abstracts = o.getString(article_txt[1]);
            content = o.getString(article_txt[2]);

            if (!TransUtil.isChinese(title)){
                //TODO:鉴于爬虫爬取格式的问题，应急补救一下
                content = content.replaceAll("]","");
                content = content.replaceAll("\\[","");

                String [] miniStrs = splitString(content);
                query = query + constructQuery(query,title) + constructQuery(query,abstracts)
                        + constructQuery(query,miniStrs[0]);
                midPaper = constructMapperParameters(query, midPaper, 2);
                System.out.println("msun--midPaper--"+ midPaper);
                try {
                    TimeUnit.SECONDS.sleep(3);
                }catch (InterruptedException e){
                    e.getStackTrace();
                }

                if (miniStrs.length > 1){
                    for (int i = 1; i < miniStrs.length; i ++){
                        appendResultStr("content", miniStrs[i], midPaper);
                        System.out.println("msun--content--"+ midPaper.getString("content"));
                        try {
                            TimeUnit.SECONDS.sleep(3);
                        }catch (InterruptedException e){
                            e.getStackTrace();
                        }
                    }
                }
                transDao.addTransTecArticle(midPaper);
            }
        }

        return 0;
    }

    private String removeN(String s){
        return s.replace("\n"," ");
    }

    private String constructQuery(String s1,String s2){
        if (!StringTools.isNullOrEmpty(s2)){
            s1 = s1 + removeN(s2) + "\n";
        }else {
            s1 = s1 + "\\\n";
        }
        return s1;
    }

    private JSONObject constructMapperParameters(String s, JSONObject o, int type){
        net.sf.json.JSONObject resultQuery;
        resultQuery = api.getTransResult(s,"en", "zh");
        JSONArray array = JSONArray.fromObject(resultQuery.get("trans_result"));

        if (type == 0){
            for (int i = 0 ; i < array.size() ; i ++){
                o.put(paper_txt[i], net.sf.json.JSONObject.fromObject(array.get(i)).get("dst"));
            }
        }
        if (type == 1){
            for (int i = 0 ; i < array.size() ; i ++){
                o.put(patent_txt[i], net.sf.json.JSONObject.fromObject(array.get(i)).get("dst"));
            }
        }
        if (type == 2){
            for (int i = 0 ; i < array.size() ; i ++){
                o.put(article_txt[i], net.sf.json.JSONObject.fromObject(array.get(i)).get("dst"));
            }
        }
        return o;
    }

    private void appendResultStr(String key, String s, JSONObject o){
        net.sf.json.JSONObject resultQuery;
        resultQuery = api.getTransResult(s,"en", "zh");
        JSONArray array = JSONArray.fromObject(resultQuery.get("trans_result"));

        for (int i = 0 ; i < array.size() ; i ++){
            o.put(key, o.getString(key) + net.sf.json.JSONObject.fromObject(array.get(i)).get("dst"));
        }
    }

    private String[] splitString(String str){
        //来源百度翻译官方API：为保证翻译质量，请将单次请求长度控制在 6000 bytes以内
        final int maxByte = 5500;
        byte[] buff = str.getBytes();
        String [] result = new String[(buff.length - 1) / maxByte + 1];
        int index = 0;
        while (index * maxByte < buff.length){
            if ((index + 1) * maxByte <= buff.length){
                result[index] = new String(Arrays.copyOfRange(buff,index*maxByte,(index+1)*maxByte));
            }else{
                result[index] = new String(Arrays.copyOfRange(buff,index*maxByte,buff.length));
            }
            index ++;
        }
        return result;
    }
}
